new Vue({
  el: '#app',
  data() {
    return {
      // 物流信息表单验证
      LogisticsCode: [{ required: true, message: '请选择快递公司', trigger: 'change' }],
      LogisticsNumbers: [{ required: true, message: '请输入快递单号', trigger: 'blur' }],
      Quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
      form: {
        Start_Date: '',
        End_Date: '',
        Article_Name: '',
        Row_Status: '',
        Order_Type: "0",
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        token: $.cookie("token"),
        Dealer_SerialNumber: '',
        page: 1,			//页数
        limit: 10,		//每页数据条数
      },
      total: 0,// 总条数
      // 获取时间
      MyDate: '',
      tableData: [], //表格数据
      SalesOrderSerialNumber: '',
      Quantity: 0,
      // 快递公司
      expressCompany: [],
      tableform: {},
      dialogVisible: false,
      // 导入订单
      dialogVisible1: false,
      //分配供应商
      dialogVisible2: false,
      // 物流信息
      OddNumbers: false,
      loading: true,
      multipleSelection: [],
      time: [],
      article_info: [],
      store_info: [],
      order_info: [],
      supplier_article: [],
      // 分配供应商
      supplier: [],
      fileList: [],
      checked: false,
      form2: [],
      form3: {
        Supplier_SerialNumber: '',
        Sales_Order_Detail_SerialNumber: '',
        Store_SerialNumber: '',
        Article_SerialNumber: '',
        Purchase_Unit_Price:'',
        Quantity: '',
        Enterprise_Info_SerialNumber: ''
      },
      sales_order_logistics: [
        {

          disabled1: false,  // 禁用物流公司
          Sales_Order_Logistics_SerialNumber: '', //主键
          Sales_Order_SerialNumber: '',   //销售价格单号
          LogisticsNumbers: '',  //物流单号
          LogisticsCode: '',  //快递公司
          Quantity: '',   //数量
        }
      ],
      statistics: {
        Collection_Amount: 0,
        Sales_Amount: 0
      },
      activeName: 'first',
      activeName1: 'first',
      formLabelWidth: '120px',
      isWares: true,
      formData: {},
      PurchaseOrderDetail: [],
      Paystages_SerialNumber: "",
      distributors: [],
      article:[],//经销商商品
      dealer:[],//经销商
    }
  },
  mounted() {
    this.getList(this.form)
    this.getData();
    console.log(this.form.Enterprise_Info_SerialNumber)
  },
  computed: {
    Dealer_Name(){
      return function (id) {
        try {
          let str = this.dealer.filter(item=>item.Dealer_SerialNumber==id)[0].Dealer_Name
          return str
        } catch (error) {
          return id
        }
      }
    },
    formatTime() {
      return function (times) {
        if (times) {
          let date = new Date(times);
          let year = date.getFullYear();
          let month = date.getMonth() + 1;
          let day = date.getDate();
          let hour = date.getHours();
          let minute = date.getMinutes();
          let second = date.getSeconds();
          month = month > 10 ? month : "0" + month;
          day = day > 10 ? day : "0" + day;
          if (hour > 10) {
            hour
          } else {
            "0" + hour;
          }
          if (minute > 10) {
            minute
          } else {
            "0" + minute
          }
          if (second > 10) {
            second
          } else {
            "0" + second
          }
          return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        } else { return '' }
      }
    },
    formatTime1() {
      return function (times) {
        if (times) {
          let date = new Date(times);
          let year = date.getFullYear();
          let month = date.getMonth() + 1;
          let day = date.getDate();
          if (month < 10) {
            month = "0" + month;
          }
          if (day < 10) {
            "0" + day
          }
          return `${year}-${month}-${day}`;
        } else { return '' }
      }
    },
  },
  methods: {
  // 点击展开
  expand(){

  },

    ribao(){
      let _this = this
      $.ajax({
        type: 'GET',
        url: DomainName + '/WeChatDailyReport',
        success: function (res) {
          _this.$message({
            type: 'success',
            message: '发放成功！'
          });
        },
        complete: function (XMLHttpRequest) {
          this_.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    deleteRow(index, rows) {
      console.log(index, 'aaaaa', rows);
      rows.splice(index, 1);
    },
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      if (row.Sales_Address == '用户自提') return { backgroundColor: 'rgba(0, 0, 0, 0.185)' }
    },
    changeTime() {
      console.log(this.Start_Date, this.End_Date)
    },
    handleChildren(row) {//供应商销售订单展开明细
      let this_ = this
      $.ajax({
        type: 'POST',
        url: DomainName + '/getPurchaseOrderPaystagesAction?token=' + $.cookie('token'),
        data: {
          Purchase_Order_SerialNumber: row.Purchase_Order_SerialNumber
        },
        success: function (res) {
          row.Children.purchase_order_paystages = res.Data
        },
        complete: function (XMLHttpRequest) {
          this_.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    onSerach() {				//查询方法
      if (this.MyDate.length != 0) {
        this.form.Start_Date = this.MyDate[0]
        this.form.End_Date = this.MyDate[1]
        console.log(this.form.Start_Date)
      }
      this.form.page = 1
      this.getList(this.form)
    },
    addContract() {
      console.log("跳转")
    },
    handleSizeChange(val) {
      this.form.page = 1;
      this.form.limit = val;
      this.getList(this.form)
    },
    handleCurrentChange(val) {
      this.form.page = val;
      this.getList(this.form)
    },
    getData() {
      let _this = this
      $.ajax({
        type: 'POST',
        url: DomainName + '/getInquiryAction',
        data: {
          token: $.cookie("token"),
          Data: 'supplier_info'
        },
        success: function (data) {
          console.log(data);
          _this.supplier_info = data
        },
        dataType: "json"
      });
      // 获取快递公司
      $.ajax({
        type: 'POST',
        url: DomainName + '/GoodsFileInquiry',
        data: {
          Data: 'logistics_company_info'
        },
        success: function (data) {
          _this.expressCompany = data
          console.log(data);
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
      //获取商品
      $.ajax({
        type: 'GET',
        url: DomainName + '/getDealer_Article?token='+$.cookie('token'),
        success: function (res) {
          _this.article = res.Data
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
      //经销商
      ajax({url:DomainName+'/getInquiryAction?token='+$.cookie("token"),type:'POST',data: { Data:'dealer_info'}},(Result)=>{
        this.dealer = Result
      },(XMLHttpRequest)=>{
        if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
          window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
        }
      })
    },
    getList(data) {
      ajax({url:DomainName+'/getSalesOrderAllAction',type:'POST',data},(Result)=>{
        console.log(Result)
        this.statistics.Collection_Amount = parseInt(Result.statistics.Collection_Amount)
        this.statistics.Sales_Amount = parseInt(Result.statistics.Sales_Amount)
        this.tableData = Result.tableData
        this.total = parseInt(Result.limit)
      },(XMLHttpRequest)=>{
        if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
          window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
        }
      })
    },
    addEnterprise() {
      let _this = this
      this.loading = true
      $.ajax({
        type: 'POST',
        data: {
          Data: JSON.stringify(_this.form2),
          token: $.cookie("token")
        },
        url: DomainName + '/setImportSalesOrder',
        success: function (res) {
          console.log(res);
          if (res.Status === 'success') {
            _this.$message({
              type: 'success',
              message: res.hasOwnProperty("Cause")?res.Cause:'提交成功'
            });
            _this.dialogVisible1 = false
            _this.getList(_this.form)
          } else {
            _this.$message({
              type: 'info',
              message: res.hasOwnProperty("Cause")?res.Cause:'提交失败'
            });
          }
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    subFile() {
      console.log($.cookie("token"))
      let _this = this
      var file = document.getElementById('inputfile').files[0]; // 获取选择的文件
      if (!file) return;
      var reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = function (e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type: 'binary' //以二进制的方式读取
        });
        var sheet0 = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
        var str = XLSX.utils.sheet_to_json(sheet0);//利用接口实现转换。
        str.forEach(item => {
          let obj =  _this.isArticle(item['规格编码']);
          let Dealer = _this.isDealer(item['经销商'])
          let Abnormal = [obj.abnormal, Dealer.abnormal]
          _this.form2.push({
            Dealer_Order_SerialNumber: item['订单号'],
            Sales_Contacts: item['收货人'],
            Sales_Phone: item['手机号码'],
            Sales_Address: item['收货地址'].replaceAll(' ','/'),
            Specifications_Name:Object.keys(obj.article).length!=0?obj.article.Article_Name:'异常数据(' + item['商品规格名称'] + ')',
            Gfbm: Object.keys(obj.article).length!=0?obj.article.Dealer_Article_SerialNumber:'异常数据(' + item['规格编码'] + ')',
            Quantity: item['发货数量'],
            Sales_Message: item['用户备注'],
            Amount:Object.keys(obj.article).length!=0?obj.article.Dealer_Amount*item['发货数量']:'',
            Sales_Amount:Object.keys(obj.article).length!=0?obj.article.Dealer_Amount*item['发货数量']:'',
            Collection_Amount:'0',
            Dealer_SerialNumber:Dealer.Dealer_SerialNumber,
            Dealer_Name:item['经销商'],
            Article_Name:Object.keys(obj.article).length!=0?obj.article.Article_Name:'异常数据(' + item['商品名称'] + ')',
            Article_SerialNumber:Object.keys(obj.article).length!=0?obj.article.Article_SerialNumber:'',
            Article_Specifications_SerialNumber:Object.keys(obj.article).length!=0?obj.article.Article_Specifications_SerialNumber:'',
            Sales_Unit_Price:Object.keys(obj.article).length!=0?obj.article.Dealer_Amount:'',
            Abnormal:!Abnormal.some(item => item == false),
          })
        })
      }
      console.log(_this.form2);
    },
    isArticle(str) {
      if (this.article.some(item => item.Dealer_Article_SerialNumber == str)) {
        return { article: this.article.filter(item => item.Dealer_Article_SerialNumber == str)[0], abnormal: true }
      } else {
        return { article: {}, abnormal: false }
      }
    },
    isDealer(str){
        if (this.dealer.some(item => item.Dealer_Name == str)) {
          return { Dealer_SerialNumber: this.dealer.filter(item => item.Dealer_Name == str)[0].Dealer_SerialNumber, abnormal: true }
        } else {
          return { Dealer_SerialNumber: '异常数据(' + str + ')', abnormal: false }
        }
    },
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      if (!row.Abnormal) return { backgroundColor: '#E6A23C' }
    },
    // 已发货
    onShipped(Sales_Order_SerialNumber, tableform, Quantity) {
      this.SalesOrderSerialNumber = Sales_Order_SerialNumber
      this.tableform = tableform
      this.Quantity = Quantity
      this.OddNumbers = true
    },
    subOddNumbers() {   // 提交物流信息
      let _this = this
      console.log(_this.sales_order_logistics)
      $.ajax({
        type: 'POST',
        data: {
          Sales_Order_SerialNumber: _this.SalesOrderSerialNumber,
          Type: '6',
          Data: JSON.stringify(_this.sales_order_logistics),
          token: $.cookie("token")
        },
        url: DomainName + '/SalesOrder_Type',
        success: function (data) {
          if (data.Status === 'success') {
            _this.$message({
              type: 'success',
              message: '提交成功'
            });
            _this.OddNumbers = false
            _this.getList(_this.form)
          } else {
            _this.$message({
              type: 'info',
              message: '提交物流失败'
            });
          }
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    addOddNumbers() {
      let _this = this
      var Num = 0
      this.sales_order_logistics.forEach(item => {
        item.Sales_Order_SerialNumber = _this.SalesOrderSerialNumber
        Num = Num + Number(item.Quantity)
      })
      console.log(Num)
      if (Num != _this.Quantity) {
        _this.$message({
          type: 'error',
          message: '输入的数据有误'
        });
        return
      }
      _this.loading = true
      if (this.tableform.Enterprise_Article_SerialNumber != this.tableform.Enterprise_Info_SerialNumber) {
        this.subOddNumbers()
      } else {
        // 生成采购订单
        $.ajax({
          type: 'POST',
          data: {
            Sales_Order_SerialNumber: _this.SalesOrderSerialNumber,
            token: $.cookie("token")
          },
          url: DomainName + '/getPurchaseOrderAddAction',
          success: function (data) {
            if (data.Status === 'success') {
              _this.subOddNumbers()
            } else if (data.Status === 'fail404') {
              _this.$message({
                type: 'info',
                message: '该供应商没有采购价格单，请先添加采购价格单'
              });
              _this.loading = false
            } else {
              _this.$message({
                type: 'info',
                message: '提交采购价格单失败'
              });
            }
          },
          complete: function (XMLHttpRequest) {
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json"
        });
      }
      // disabled
      // if (this.isChecked()) {
      //   _this.$message.error('请填写物流单号')
      //   _this.loading = false
      // } else {

      // }
    },
    // isChecked() {
    //   this.sales_order_logistics.forEach(item => {
    //     console.log(item.checked)
    //     if (!item.checked && item.LogisticsNumbers == '') {
    //       return true;
    //     }
    //   })
    //   return false;
    // },
    // 清空物流信息
    qing_sales_order_logistics() {
      this.sales_order_logistics = [{     //采购价格单
        Sales_Order_Logistics_SerialNumber: '', //主键
        Sales_Order_SerialNumber: '',   //销售价格单号
        LogisticsNumbers: '',  //快递公司
        LogisticsCode: '',  //物流单号
        Quantity: '',   //数量
      }]
      this.checked = false
    },
    // 已送达
    delivered(Sales_Order_SerialNumber, Row_Status) {
      console.log(Row_Status);
      let _this = this;
      if (Row_Status == '6') {
        this.$confirm('更改订单状态为\'已送达\', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          $.ajax({
            type: 'POST',
            data: {
              Sales_Order_SerialNumber,
              Type: '7'
            },
            url: DomainName + '/SalesOrder_Type',
            success: function (data) {
              if (data.Status === 'success') {
                _this.$message({
                  type: 'success',
                  message: '提交成功',
                });
                _this.getList(_this.form)
              } else {
                _this.$message({
                  type: 'info',
                  message: '提交失败'
                });
              }
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            },
            dataType: "json"
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消提交退款申请！'
          });
        });
      }
    },
    // 是否自提
    SelfPickup() {
      this.sales_order_logistics.forEach(item => {
        if (this.checked) {
          item.disabled1 = true
          item.LogisticsCode = ''
          item.LogisticsNumbers = '自提'
        } else {
          item.disabled1 = false
          item.LogisticsNumbers = ''
        }
      })
    },
    // 新增物流信息
    add_sales_order_logistics() {
      if (this.Quantity == this.sales_order_logistics.length) {
        this.$message({
          message: `总数为${this.Quantity},不可以在新增了`,
          type: 'warning'
        })
        return
      }
      this.sales_order_logistics.push({     //采购价格单
        Sales_Order_Logistics_SerialNumber: '', //主键
        Sales_Order_SerialNumber: '',   //销售价格单号
        LogisticsNumbers: '',  //快递公司
        LogisticsCode: '',  //物流单号
        Quantity: '',   //数量
        checked: false
      })
    },
    remove_sales_order_logistics() {
      if (this.sales_order_logistics.length > 1) {
        this.sales_order_logistics.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    // 分配供应商
    AddMember(row) {
      let _this = this
      this.SalesOrderSerialNumber = row.Sales_Order_SerialNumber
      console.log(row.Enterprise_Article_SerialNumber, row.Enterprise_Info_SerialNumber)
      if (row.Row_Status == '1' || row.Row_Status == '9') {
        if (row.Enterprise_Article_SerialNumber != row.Enterprise_Info_SerialNumber) {
          return this.$message.error("该商品供应商是外企业，不可更改")
        }
        //初始化
        this.multipleSelection = []
        this.supplier = []
        this.form3 = {}
        this.dialogVisible2 = true
        // 获取卖此商品供应商
        $.ajax({
          type: 'POST',
          data: {
            Article_SerialNumber: row.Article_SerialNumber,
            Enterprise_Info_SerialNumber: row.Enterprise_Info_SerialNumber,
            token: $.cookie("token")
          },
          url: DomainName + '/getSupplierArticleAction',
          success: function (data) {
            console.log(data)
            _this.supplier = data
          },
          complete: function (XMLHttpRequest) {
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json"
        });


        //获取数据
        this.multipleSelection.push(row)
        // this.supplier = this.supplier_article.filter(item => {
        //   return item.Article_SerialNumber == row.Article_SerialNumber
        // })
        this.form3 = {
          Enterprise_Info_SerialNumber: row.Enterprise_Info_SerialNumber,
          Sales_Order_Detail_SerialNumber: row.Sales_Order_Detail_SerialNumber,
          Store_SerialNumber: row.Store_SerialNumber,
          Article_SerialNumber: row.Article_SerialNumber,
          Quantity: row.Quantity,
          Supplier_SerialNumber: ''
        }
      } else {
        this.$message.error("该订单状态不满足分配供应商条件")
      }
    },
    // val(Arr) {
    //   for (let i = 0; i < Arr.length; i++) {
    //     if (Arr[i].Supplier_SerialNumber.length == 0) {
    //       return false
    //     }
    //   }
    //   return true
    // },
    // 切换导航栏
    handleClick(event) {
      _this = this
      // 全部
      if (event.index == 0) {
        this.form.Row_Status = ""
        this.getList(this.form)
      }
      // 未付款 
      else if (event.index == 1) {
        this.form.Row_Status = 0
        this.getList(this.form)
      }
      // 已付款
      else if (event.index == 2) {
        this.form.Row_Status = 1
        this.getList(this.form)
      }
      // 待发货
      else if (event.index == 3) {
        this.form.Row_Status = 9
        this.getList(this.form)
      }
      // 发货中
      else if (event.index == 4) {
        this.form.Row_Status = 6
        this.getList(this.form)
      }
      // 已送达
      else if (event.index == 5) {
        this.form.Row_Status = 7
        this.getList(this.form)
      }
      // 当日发货
      else if (event.index == 6) {
        this.form.Row_Status = 1
        let obj = {
          Start_Date: this.formatTime1(new Date().getTime() - 86400000) + ' 15:00:00',
          End_Date: this.formatTime1(new Date().getTime()) + ' 15:00:00',
          Article_Name: this.form.Article_Name,
          Row_Status: this.form.Row_Status,
          Enterprise_Info_SerialNumber: this.form.Enterprise_Info_SerialNumber,
          token: $.cookie("token"),
          page: this.form.page,			//页数
          limit: this.form.limit,
        }
        this.getList(obj)
      }
      // 已退款
      else if (event.index == 7) {
        this.form.Row_Status = 4
        this.getList(this.form)
      }
    },
    handleClick1(event) {
      if (event.index == 0) {
        this.form.Row_Status = ""
        this.getList(this.form)
      }
      // 未付款 
      else if (event.index == 1) {
        this.form.Row_Status = 0
        this.getList(this.form)
      }
      // 已付款
      else if (event.index == 2) {
        this.form.Row_Status = 1
        this.getList(this.form)
      }
      // 待发货
      else if (event.index == 3) {
        this.form.Row_Status = 9
        this.getList(this.form)
      }
      // 发货中
      else if (event.index == 4) {
        this.form.Row_Status = 6
        this.getList(this.form)
      }
      // 已送达
      else if (event.index == 5) {
        this.form.Row_Status = 7
        this.getList(this.form)
      }
    },
    handleSupplier(e){
      this.form3.Purchase_Unit_Price = this.supplier.filter(item=>item.Supplier_SerialNumber==e)[0].Purchase_Unit_Price
    },
    // 提交供应商信息
    submitForm() {
      let _this = this
      console.log(this.form3);
      console.log(1, this.SalesOrderSerialNumber)
      if (!_this.form3.Supplier_SerialNumber) return _this.$message('请选择供应商');
      _this.loading = true
      // 更改状态
      $.ajax({
        type: 'POST',
        data: {
          Sales_Order_SerialNumber: _this.SalesOrderSerialNumber,
          Supplier_SerialNumber:_this.form3.Supplier_SerialNumber,
          Purchase_Unit_Price:_this.form3.Purchase_Unit_Price,
          Type: '9'
        },
        url: DomainName + '/SalesOrder_Type',
        success: function (data) {
          if(data.Status=='success'){
            _this.dialogVisible2 = false
            _this.getList(_this.form)
          }
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
     
      // 分配供应商
      // $.ajax({
      //   type: 'POST',
      //   data: {
      //     Data: JSON.stringify({
      //       sales_order_supplier: [_this.form3]
      //     }),
      //     token: $.cookie("token")
      //   },
      //   url: DomainName + '/getAddAction',
      //   success: function (data) {
      //     console.log(data)
      //     _this.WriteBackOrder()
      //   },
      //   complete: function (XMLHttpRequest) {
      //     if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
      //       window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
      //     }
      //   },
      //   dataType: "json"
      // });
    },
    // WriteBackOrder() {
    //   $.ajax({
    //     url: DomainName + '/getInquiryIDOriginal',
    //     type: 'POST',
    //     data: {
    //       Data: 'sales_order_detail',
    //       Primary_Key_Name: 'Sales_Order_Detail_SerialNumber',
    //       Primary_Key: _this.form3.Sales_Order_Detail_SerialNumber,
    //       token: $.cookie("token")
    //     },
    //     success: function (res) {
    //       if (res.length == 1) {
    //         res[0].Supplier_SerialNumber = _this.form3.Supplier_SerialNumber
    //         detel = res[0];
    //         let data = { Data: JSON.stringify({ Modify: { sales_order_detail: [detel] } }) };
    //         $.ajax({
    //           url: DomainName + '/GoodsFileEdit',
    //           type: 'POST',
    //           data,
    //           success: function (res) {
    //             if (res.Status === 'success') {
    //               _this.$message.success('分配供应商成功')
    //               _this.dialogVisible2 = false
    //               _this.getList(_this.form)
    //             } else {
    //               _this.$message.error("操作失败，请稍后再试")
    //             }
    //           },
    //           error: function () {
    //             _this.$message.error("操作失败，请稍后再试")
    //           },
    //           complete: function () { _this.loading = false }
    //         })
    //       }
    //     },
    //     complete: function (XMLHttpRequest) {
    //       _this.loading = false
    //       if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
    //         window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
    //       }
    //     },
    //     dataType: "json"
    //   });
    // },
    accMul(arg1, arg2) {
      let m = 0, s1 = arg1.toString(), s2 = arg2.toString();
      try { m += s1.split(".")[1].length } catch (e) { }
      try { m += s2.split(".")[1].length } catch (e) { }
      return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
    },
    refund(Sales_Order_SerialNumber) {
      let _this = this
      this.$confirm('提交退款申请, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        $.ajax({
          type: 'POST',
          data: {
            Sales_Order_SerialNumber: Sales_Order_SerialNumber,
            token: $.cookie("token")
          },
          url: DomainName + '/getChatRefundNativeAction',
          success: function (data) {
            if (data.Status === 'success') {
              _this.$message({
                type: 'success',
                message: '提交成功'
              });
              _this.getList(_this.form)
            } else {
              _this.$message({
                type: 'info',
                message: '提交失败'
              });
            }
          },
          complete: function (XMLHttpRequest) {
            _this.loading = false
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
          dataType: "json"
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消提交退款申请！'
        });
      });
    },
    showMember(Sales_Order_SerialNumber) {
      sessionStorage.setItem("Sales_Order_SerialNumber", Sales_Order_SerialNumber)
      window.location.href = './show.html?Sales_Order_SerialNumber=' + Sales_Order_SerialNumber
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    validate(arr) {
      if (arr[0] == undefined || arr[1] == undefined) {
        this.$message.error('请选择开始时间和结束时间')
        return false
      } else if (arr[0] != undefined && arr[1] != undefined) {
        return true
      }
    },
    // 时间筛选
    onDetails() {
      if (this.validate(this.time)) {
        sessionStorage.setItem("start-date", this.time[0])
        sessionStorage.setItem("end-date", this.time[1])
        // window.location.href = '../xiaoshouDetails/Details.html'
      }
    },
    beforeRemove(file, fileList) {
      this.fileList.pop()
      this.form2 = []
    },
    onExcel() {
      /* generate workbook object from table */
      //  .table要导出的是哪一个表格
      var wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        //  name+'.xlsx'表示导出的excel表格名字
        saveAs(
          new Blob([wbout], {
            type: "application/octet-stream"
          }),
          "销售订单" + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    uploadDetails(file) {
      this.fileList.push({
        name: file.name,
        url: file.type
      })
      let _this = this
      var reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = function (e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type: 'binary' //以二进制的方式读取
        });
        var sheet0 = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
        var str = XLSX.utils.sheet_to_json(sheet0);//利用接口实现转换。
        console.log(str);
        //将整体数据分解成每一条，一条上传一次

        //1.将接受到数组便利
        str.forEach(item => {
          _this.form2.push({
            Sales_Order_SerialNumber: item['订单号'],
            Sales_Contacts: item['收货人'],
            Sales_Phone: item['手机号码'],
            Sales_Address: item['收货地址'],
            Wliugs: item['物流公司'],
            Sqname: item['商品名称'],
            Specifications_Name: item['商品规格名称'],
            Gfbm: item['规格编码'],
            Quantity: item['发货数量'],
            Sales_Message: item['用户备注'],
            Amount:'',
            Sales_Date:'',
            Sales_Amount:'',
            Collection_Amount:'',
            Dealer_Name:'',
            Dealer_SerialNumber:'',
            App_ID:'',
            Article_Name:'',
            Article_SerialNumber:'',
            Article_Specifications_SerialNumber:'',
            Quantity:'',
            Sales_Unit_Price:''
          })
        })
      }
    },
    handleOperate(row, Trading_Detail_SerialNumber) {//确认
      const this_ = this
      if (row.Row_Status == '1') {//收款改主表+明细 并生成发货单
        this_.loading = true
        $.ajax({
          url: DomainName + '/TableIDEdit?token=' + $.cookie("token"),
          type: 'POST',
          data: {
            TableName:'purchase_order',
            Primary_Key: JSON.stringify({ Purchase_Order_SerialNumber:row.Purchase_Order_SerialNumber }),
            Modify: JSON.stringify({Row_Status:'3',Confirm_Amount:res.Paid_Amount}),
          },
          success: function (res) {
            if(res.Status=='success'&&row.Independence=='0'){
              this_.Delivery((res)=>{
                if (res.Status == 'success') {
                  this_.loading = false
                  this_.getList(this_.form)
                  this_.$message({
                    message: '成功',
                    type: 'success'
                  })
                }
              })
            }else if(res.Status=='success'&&row.Independence=='1'){
              this_.loading = false
              this_.getList(this_.form)
              this_.$message({
                message: '成功',
                type: 'success'
              })
            }
            // if (res.purchase_order.length == 1) {
            //   res.purchase_order[0].Row_Status = '3'
            //   res.purchase_order[0].Confirm_Amount = res.purchase_order[0].Paid_Amount
            //   let data = {
            //     Data: JSON.stringify({
            //       Modify: { purchase_order: res.purchase_order }
            //     })
            //   }

              // this_.AddInquiry(data, () => {
              //   $.ajax({
              //     url: DomainName + '/getDeliveryOrderAction?token=' + $.cookie("token"),
              //     type: 'POST',
              //     data: {
              //       Unit_Price_SerialNumber: row.Unit_Price_SerialNumber,
              //       Purchase_Order_SerialNumber: row.Purchase_Order_SerialNumber,
              //       Quantity: row.Quantity,
              //       Packing: row.Packing,
              //       Independence: row.Independence,
              //       Article_SerialNumber: row.Article_SerialNumber,
              //       Collection_Date: row.Collection_Date,
              //       Enterprise_Info_SerialNumber: $.cookie("enterprise")
              //     },
              //     success: function (res) {
              //       console.log(res)
              //       if (res.Status == 'success') {
              //         this_.loading = false
              //         this_.getList(this_.form)
              //         this_.$message({
              //           message: '成功',
              //           type: 'success'
              //         })
              //       }
              //     },
              //     complete: function (XMLHttpRequest) {
              //       this_.loading = false
              //       if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              //         window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              //       }
              //     },
              //     dataType: "json"
              //   });
              // })
        //     }
          }
        })
      } else {//非首款只改明细
        this_.loading = true
        $.ajax({
          url: DomainName + '/getSubtableInquiryOriginal?token=' + $.cookie("token"),
          type: 'POST',
          data: {
            Primary_Key: row.Purchase_Order_SerialNumber,
            JSONObject: JSON.stringify({ purchase_order: { purchase_order_paystages: {} } }),
          },
          success: function (res) {
            if (res.purchase_order.length == 1) {
              res.purchase_order[0].Confirm_Amount = res.purchase_order[0].Paid_Amount
              res.purchase_order[0].Children.purchase_order_paystages.forEach(item => {
                if (item.Trading_Detail_SerialNumber == Trading_Detail_SerialNumber && item.Row_Status == '1') {
                  item.Row_Status = '2'
                }
              })
              let data = {
                Data: JSON.stringify({
                  Modify: { purchase_order: res.purchase_order }
                })
              }
              this_.AddInquiry(data, () => {
                this_.getList(this_.form)
                this_.loading = false
                this_.$message({
                  message: '成功',
                  type: 'success'
                })
              })
            }
          },
          complete: function (XMLHttpRequest) {
            this_.loading = false
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          },
        })
      }
    },
    Delivery(row,callback){
      $.ajax({
        url: DomainName + '/getDeliveryOrderAction?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Unit_Price_SerialNumber: row.Unit_Price_SerialNumber,
          Purchase_Order_SerialNumber: row.Purchase_Order_SerialNumber,
          Quantity: row.Quantity,
          Packing: row.Packing,
          Independence: row.Independence,
          Article_SerialNumber: row.Article_SerialNumber,
          Collection_Date: row.Collection_Date,
          Enterprise_Info_SerialNumber: $.cookie("enterprise")
        },
        success: function (res) {
          callback(res);
        },
        complete: function (XMLHttpRequest) {
          this_.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    },
    AddInquiry(data, callback) {//回调修改原值
      $.ajax({
        url: DomainName + '/getEditAction?token=' + $.cookie("token"),
        type: 'POST',
        data,
        success: function (res) {
          if (res.Status == 'success') {
            callback()
          }
        },
        dataType: "json"
      });
    },
    RadioChange(e) {//切换用户or经销商
      console.log(e)
      this.tableData = []
      this.form.page = 1
      this.getList(this.form)
      if (e == '1') {
        this.Getdistributors()
      }
    },
    Pricethousands(num) {//转千分位
      return thousands(num)
    },
    SelectDistributors() {
      this.form.page = 1
      this.getList(this.form)
    },
    handlePurchase(row, rowfu) {//经销商明细退款
      // if(row.Row_Status == '1'){
      let this_ = this
      this_.loading = true
      $.ajax({
        url: DomainName + '/getPurchaseWeChatRefundAction?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Purchase_Order_Paystages_SerialNumber: row.Purchase_Order_Paystages_SerialNumber,
        },
        success: function (res) {
          if (res.Status == 'success') {
            this_.handleChildren(rowfu)
            this_.$message({
              message: '申请成功',
              type: 'success'
            })
          }
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
      // }
    },
    Getdistributors() {//获取所有可选择的经销商
      const _this = this
      $.ajax({
        url: DomainName + '/getInquiryAction?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Data: 'dealer_info',
        },
        success: function (res) {
          console.log(res)
          _this.distributors = res
        },
        dataType: "json"
      });
    },
  },
})